<template>
    <div class="register-page">
        <div class="register-bg">
            <el-form class="register-form" v-if="pageFlag == 'register'" ref="registerForm" :model="registerForm"
                :rules="rules">
                <div class="hidden-title">USER / REGISTER</div>
                <div class="main-title">智核NousCore注册</div>

                <el-radio-group v-model="tableName" style="margin-bottom: 20px;">
  <el-radio-button label="user">学生账号</el-radio-button>
  <el-radio-button label="teacher">老师账号</el-radio-button>
</el-radio-group>

                <el-form-item class="form-item" prop="username">
                    <div class="form-label" :class="changeRules('username') ? 'required' : ''">用户账号：</div>
                    <el-input v-model="registerForm.username" placeholder="请输入用户账号" />
                </el-form-item>

                <el-form-item class="form-item" prop="password">
                    <div class="form-label" :class="changeRules('password') ? 'required' : ''">密码：</div>
                    <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" />
                </el-form-item>

                <el-form-item class="form-item" prop="password2">
                    <div class="form-label" :class="changeRules('password') ? 'required' : ''">确认密码：</div>
                    <el-input v-model="registerForm.password2" type="password" placeholder="请再次输入密码" />
                </el-form-item>

                <el-form-item class="form-item" prop="name">
                    <div class="form-label" :class="changeRules('name') ? 'required' : ''">用户姓名：</div>
                    <el-input v-model="registerForm.name" placeholder="请输入用户姓名" />
                </el-form-item>

                <el-form-item class="form-item" v-if="tableName == 'user'" prop="gender">
                    <div class="form-label" :class="changeRules('gender') ? 'required' : ''">性别：</div>
                    <el-select v-model="registerForm.gender" placeholder="请选择性别">
                        <el-option v-for="(item, index) in genderOptions" :key="index" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item class="form-item" prop="email">
                    <div class="form-label" :class="changeRules('email') ? 'required' : ''">邮箱：</div>
                    <el-input v-model="registerForm.email" placeholder="请输入您的邮箱" style="width: calc(100% - 120px); display: inline-block; margin-right: 10px;" />
                    <el-button type="primary" @click="getVerificationCode" :disabled="countdown > 0">{{ countdown > 0 ? `重新发送 (${countdown}s)` : '获取验证码' }}</el-button>
                </el-form-item>

                <el-form-item class="form-item" prop="verificationCode">
                    <div class="form-label" :class="changeRules('verificationCode') ? 'required' : ''">验证码：</div>
                    <el-input v-model="registerForm.verificationCode" placeholder="请输入验证码" />
                </el-form-item>

                <el-form-item label="头像" prop="avatar">
                    <file-upload
                        tip="点击上传头像"
                        action="api/upload/uploadAvatar"
                        :limit="1"
                        @change="avatarUploadChange"
                        :fileUrls="registerForm.avatar ? registerForm.avatar:''"
                    ></file-upload>
                </el-form-item>

                <el-button class="submit-btn" type="primary" @click="submitForm('registerForm')">注册</el-button>
                <el-button class="reset-btn" @click="resetForm('registerForm')">重置</el-button>
                <router-link class="login-link" to="/login">已有账户登录</router-link>

                <div class="idea1"></div>
                <div class="idea2"></div>
            </el-form>
        </div>
    </div>
</template>

<script>
export default {
    //数据集合
    data() {
        return {
            baseUrl: this.$config.baseUrl,
            pageFlag: '',
            tableName: '',

            registerForm: {
                username: '',
                password: '',
                password2: '',
                name: '',
                gender: '',
                email: '', // 确保这个字段是用于邮箱
                verificationCode: '', // 新增：验证码字段
                avatar: ''
            },
            forgetForm: {},
            rules: {},
            requiredRules: {},
            genderOptions: [],
            avatarRawFile: null,
            countdown: 0, // 倒计时变量
            countdownTimer: null // 倒计时计时器
        }
    },
    mounted() {
        if (this.$route.query.pageFlag == 'register') {
            this.tableName = this.$route.query.role;
            if (this.tableName == 'user') {
                this.registerForm = {
                    username: '',
                    password: '',
                    password2: '',
                    name: '',
                    gender: '',
                    email: '',
                    verificationCode: '', // 初始化验证码字段
                    avatar: '',
                }
            }
            // 确保 requiredRules 中也包含 email 和 verificationCode
            if ('user' == this.tableName) {
                                this.rules.username = [
                    { required: true, message: '请输入用户账号', trigger: 'blur' },
                    { min: 6, max: 12, message: '账号长度必须在 6 到 12 个字符之间', trigger: 'blur' }
                ];
                this.rules.password = [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '密码长度必须在 6 到 12 个字符之间', trigger: 'blur' }
                ];
                this.requiredRules.name = [{ required: true, message: '请输入用户姓名', trigger: 'blur' }]
                this.requiredRules.email = [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }]
                this.requiredRules.verificationCode = [{ required: true, message: '请输入验证码', trigger: 'blur' }]
            }
        }
    },
    created() {
        this.pageFlag = this.$route.query.pageFlag;
        if (this.$route.query.pageFlag == 'register') {
            if ('user' == this.tableName) {
                this.rules.username = [
                    { required: true, message: '请输入用户账号', trigger: 'blur' },
                    { min: 6, max: 12, message: '账号长度必须在 6 到 12 个字符之间', trigger: 'blur' }
                ];
                this.rules.password = [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '密码长度必须在 6 到 12 个字符之间', trigger: 'blur' }
                ];
                this.rules.name = [{ required: true, message: '请输入用户姓名', trigger: 'blur' }];
                this.rules.email = [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }];
                this.rules.verificationCode = [{ required: true, message: '请输入验证码', trigger: 'blur' }];
            }
            this.genderOptions = "男,女".split(',');
        }
    },
    //方法集合
    methods: {
        changeRules(name) {
            if (this.requiredRules[name]) {
                return true
            }
            return false
        },
        // 获取uuid (此方法在此场景下未直接使用，保留)
        getUUID() {
            return new Date().getTime();
        },

        avatarUploadChange(file) {
            if (!file) {
                this.registerForm.avatar = "";
                return;
            }
            if (file instanceof File) {
                let formData = new FormData();
                formData.append("file", file);

                this.$http.post("api/upload/uploadAvatar", formData, {
                    headers: {
                        // 如果有认证头，例如token，可以在这里添加
                        // 'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                }).then(({ data }) => {
                    if (data.code === 0) {
                        this.registerForm.avatar = data.url; 
                        this.$message.success("头像上传成功");
                    } else {
                        this.$message.error(data.msg || "上传失败");
                    }
                }).catch(() => {
                    this.$message.error("上传失败");
                });
            } else if (typeof file === "string") {
                this.registerForm.avatar = file;
            } else if (file?.response?.code === 0) {
                this.registerForm.avatar = file.response.url;
            } else {
                this.$message.error("头像上传失败");
            }
        },

        // 新增：获取验证码方法
        async getVerificationCode() {
            // 1. 验证邮箱格式
            if (!this.registerForm.email) {
                this.$message.error('请输入邮箱地址！');
                return;
            }
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(this.registerForm.email)) {
                this.$message.error('请输入正确的邮箱格式！');
                return;
            }

            // 2. 调用后端接口发送验证码
            try {
                const response = await this.$http.post(`api/email/send-verification-code?email=${this.registerForm.email}`);
                const res = response.data;

                if (res && res.code === 0) {
                    this.$message.success(res.msg || '验证码已发送，请查收！');
                    this.startCountdown(); // 开始倒计时
                } else {
                    this.$message.error((res && res.msg) || '发送验证码失败，请稍后再试！');
                }
            } catch (error) {
                console.error('发送验证码请求失败:', error);
                this.$message.error('发送验证码请求失败，请检查网络或后端服务！');
            }

        },

        // 倒计时逻辑
        startCountdown() {
            this.countdown = 60; // 设置倒计时秒数，例如60秒
            this.countdownTimer = setInterval(() => {
                if (this.countdown > 0) {
                    this.countdown--;
                } else {
                    clearInterval(this.countdownTimer);
                    this.countdownTimer = null;
                }
            }, 1000);
        },

        // 提交注册表单
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (!valid) return;

                if (this.registerForm.password !== this.registerForm.password2) {
                    this.$message.error('两次密码输入不一致');
                    return;
                }

                
                const user = {
                    username: this.registerForm.username,
                    password: this.registerForm.password,
                    name: this.registerForm.name,
                    gender: this.registerForm.gender,
                    email: this.registerForm.email,
                    verificationCode: this.registerForm.verificationCode,
                    avatar: this.registerForm.avatar
                };

                const teacher = {
                    username: this.registerForm.username,
                    password: this.registerForm.password,
                    name: this.registerForm.name,
                    avatar: this.registerForm.avatar,
                    email: this.registerForm.email,
                    verificationCode: this.registerForm.verificationCode,
                };

                try {
                    const apiPath = this.tableName === 'teacher' ? 'teacher/register' : 'user/register';

                    const registerResponse = await this.$http.post(apiPath, user);

                    if (registerResponse.data.code === 0) {
                        this.$message.success("注册成功");
                        this.$router.push("/login");
                    } else {
                        // 后端返回的错误信息会直接显示，包括验证码错误
                        this.$message.error(registerResponse.data.msg);
                    }
                } catch (error) {
                    console.error('注册请求失败:', error);
                    this.$message.error('注册请求失败，请检查网络或后端服务！');
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            // 重置时清除倒计时
            clearInterval(this.countdownTimer);
            this.countdown = 0;
            this.countdownTimer = null;
        }
    },
    beforeDestroy() {
        // 在组件销毁前清除计时器，防止内存泄漏
        if (this.countdownTimer) {
            clearInterval(this.countdownTimer);
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.register-page {
	min-height: 100vh;
	width: 100%;
	position: relative;
	overflow: hidden;
}

.register-bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: url("https://nous-core.obs.cn-north-4.myhuaweicloud.com/images/%E5%AD%A6%E4%B9%A0.jpg");
	background-size: cover;
	background-position: center center;
	background-repeat: no-repeat;
	z-index: 1;
}

.register-form {
	position: fixed;
	right: 10%;
	/* 调整右侧间距 */
	top: 50%;
	transform: translateY(-50%);
	width: 30vw;
	padding: 20px;
	border-radius: 0px;
	background: #fff;
	height: auto;
	z-index: 2;
	max-height: 90vh;
	/* 防止表单过高 */
	overflow-y: auto;
	/* 如果内容过多可以滚动 */
	/* 隐藏滚动条但保留滚动功能 */
	scrollbar-width: none;
	/* Firefox */
	-ms-overflow-style: none;
	/* IE和Edge */
}

.hidden-title {
	width: 100%;
	margin: 0 0 10px 0;
	line-height: 44px;
	font-size: 20px;
	color: rgba(64, 158, 255, 1);
	text-align: center;
	display: none;
}

.main-title {
	width: 80%;
	margin: 20px auto 10px;
	line-height: 44px;
	font-size: 28px;
	color: #333;
	text-align: left;
}

.form-item {
	width: auto;
	padding: 0;
	margin: 0 auto 15px 10%;
	background: none;
	height: auto;
}

.form-label {
	width: 100%;
	line-height: 36px;
	font-size: 14px;
	color: #333;
}

.form-label.required:before {
	content: "*";
	color: red;
	margin-right: 4px;
}

.submit-btn {
	border: 0;
	cursor: pointer;
	padding: 0 10px;
	margin: 20px auto 5px 10%;
	color: #fff;
	display: block;
	min-width: 400px;
	outline: none;
	border-radius: 4px;
	background: #ffc000;
	width: auto;
	font-size: 16px;
	height: 44px;
}

.reset-btn {
	border: 0;
	cursor: pointer;
	padding: 0 10px;
	margin: 0px auto 0px 10%;
	color: #666;
	text-align: right;
	display: block;
	min-width: 400px;
	outline: none;
	border-radius: 8px;
	background: none;
	width: auto;
	font-size: 16px;
	height: 44px;
}

.login-link {
	cursor: pointer;
	padding: 0 10%;
	margin: 0 0 40px;
	color: rgba(159, 159, 159, 1);
	display: inline-block;
	line-height: 1;
	font-size: 14px;
	text-decoration: none;
}

.idea1,
.idea2 {
	width: 100%;
	background: red;
	display: none;
	height: 40px;
}

.idea2 {
	background: blue;
}

.container {
	position: relative;
	background: url("https://nous-core.obs.cn-north-4.myhuaweicloud.com/images/%E5%AD%A6%E4%B9%A0.jpg");

	.el-input {
		width: auto;
	}

	.el-date-editor.el-input {
		width: auto;
	}

	.el-form-item /deep/ .el-form-item__content {
		display: block;
		width: 100%;
	}

	.rgs-form .el-input /deep/ .el-input__inner {
		border: 1px solid #ddd;
		border-radius: 4px;
		padding: 0 10px;
		outline: none;
		color: #666;
		width: 100%;
		font-size: 14px;
		min-width: 400px;
		height: 40px;
	}

	.rgs-form .el-select /deep/ .el-input__inner {
		border: 1px solid #ddd;
		border-radius: 4px;
		padding: 0 10px;
		outline: none;
		color: #666;
		width: 100%;
		font-size: 14px;
		min-width: 400px;
		height: 40px;
	}

	.rgs-form .el-date-editor /deep/ .el-input__inner {
		border: 1px solid #ddd;
		border-radius: 4px;
		padding: 0 10px 0 30px;
		outline: none;
		color: #666;
		width: 1;
		font-size: 14px;
		min-width: 400px;
		height: 40px;
	}

	.rgs-form .el-date-editor /deep/ .el-input__inner {
		border: 1px solid #ddd;
		border-radius: 4px;
		padding: 0 10px 0 30px;
		outline: none;
		color: #666;
		width: 1;
		font-size: 14px;
		min-width: 400px;
		height: 40px;
	}

	.rgs-form /deep/ .el-upload--picture-card {
		background: transparent;
		border: 0;
		border-radius: 0;
		width: auto;
		height: auto;
		line-height: initial;
		vertical-align: middle;
	}

	.rgs-form /deep/ .upload .upload-img {
		border: 1px solid #ddd;
		cursor: pointer;
		border-radius: 4px;
		color: #999;
		width: 160px;
		font-size: 32px;
		line-height: 80px;
		text-align: center;
		height: 80px;
	}

	.rgs-form /deep/ .el-upload-list .el-upload-list__item {
		border: 1px solid #ddd;
		cursor: pointer;
		border-radius: 4px;
		color: #999;
		width: 160px;
		font-size: 32px;
		line-height: 80px;
		text-align: center;
		height: 80px;
	}

	.rgs-form /deep/ .el-upload .el-icon-plus {
		border: 1px solid #ddd;
		cursor: pointer;
		border-radius: 4px;
		color: #999;
		width: 160px;
		font-size: 32px;
		line-height: 80px;
		text-align: center;
		height: 80px;
	}
}

.required {
	position: relative;
}

.required::after {
	color: red;
	left: -10px;
	position: absolute;
	content: "*";
}
</style>